# === load relevant libraries
library(data.table)
library(ggplot2)
library(DescTools)
library(plm)
library(lfe)
library(dplyr)
library(sandwich)

rm(list = ls())

# get style data
data = readRDS('input_data/morningstar_style_data.RDS')
data[, yyyy := floor(yyyymm/100)]
data[, mm := yyyymm - 100*yyyy]
data[, post := ifelse(mm %in% 7:12, 1, 0)] # indicator: post reform
data[, ret := ret * 100]

# get style ranking based on predicted rating changes
tmp  = readRDS('input_data/predicted_rating_change_styles.RDS')
data = merge(data, tmp, by = c('yyyy','category')); rm(tmp, this)

# indicator variables to interact with post-reform dummy
data[, top_style := ifelse(rank == 9, 'yes', '')]
data[, rank_top_half := ifelse(rank %in% 4:9, 'yes', '')]
options(warn = -1)

# = regression outputs

# columns 1 to 3
summary(felm(ret ~ as.factor(post) * rank | yyyymm + category | 0 | yyyymm, data[yyyy == 2002]))
summary(felm(ret ~ as.factor(post) * rank_top_half | yyyymm + category | 0 | yyyymm, data[yyyy == 2002]))
summary(felm(ret ~ as.factor(post) * top_style | yyyymm + category | 0 | yyyymm, data[yyyy == 2002]))

# columns 4 to 6
summary(felm(ret ~ as.factor(post) * rank | yyyymm + category | 0 | yyyymm, data[yyyy != 2002]))
summary(felm(ret ~ as.factor(post) * rank_top_half | yyyymm + category | 0 | yyyymm, data[yyyy != 2002]))
summary(felm(ret ~ as.factor(post) * top_style | yyyymm + category | 0 | yyyymm, data[yyyy != 2002]))

